package org.wlc.demov1;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 王立朝
 * @date 2022/5/13
 * @description:
 */
public class Admin {
    private int cursorIdx = 0;
    private List<ConfigMemento> mementoList = new ArrayList<ConfigMemento>();
    private Map<String, ConfigMemento> mementoMap = new ConcurrentHashMap<String, ConfigMemento>();

    /**
     * 新增
     * @param memento
     */
    public void append(ConfigMemento memento){
        mementoList.add(memento);
        mementoMap.put(memento.getConfigFile().getVersion(),memento);
        cursorIdx++;

    }

    /**
     * 会滚
     * @return
     */
    public ConfigMemento undo(){
        if(--cursorIdx<-0){
            return mementoList.get(0);
        }
        return mementoList.get(cursorIdx);
    }

    /**
     * 返回
     * @return
     */
    public ConfigMemento redo(){
        if(++cursorIdx>mementoList.size()){
           return mementoList.get(mementoList.size()-1);
        }
        return mementoList.get(cursorIdx);
    }

    /**
     * 根据版本号获取备忘录
     * @param version
     * @return
     */
    public ConfigMemento get(String version){
        return mementoMap.get(version);
    }
}
